package ru.btabank.dom.xpath.expression;

import java.util.ArrayList;

import org.w3c.dom.Node;

import ru.btabank.dom.xpath.XPathException;

public class NamespaceUriFunction extends FunctionCall {

    public NamespaceUriFunction() {
        super();
    }

    public Object evaluate(NodeSet context) throws XPathException {
        ArrayList values = super.evaluateValues(context);
        Object value;

        if (values.size() != 1)
            throw new XPathException("namespace-uri() function requires one argument.");
        else
            value = values.get(0);

        if (!(value instanceof NodeSet)) {
            throw new XPathException("namespace-uri() function can only be used for node-sets");
        }

        NodeSet nodeSet = (NodeSet)value;
        if (nodeSet.getLength() == 0) {
            return "";
        }

        Node node = nodeSet.item(0);
        if (node.getNodeType() == Node.ATTRIBUTE_NODE || node.getNodeType() == Node.ELEMENT_NODE) {
            String uri = node.getNamespaceURI();
            if (uri == null)
                return "";
            else
                return uri;
        } else
            return "";
    }
}
